﻿using System;
using System.Collections.Generic;
using System.IO;
using FileMerge.Models;
using Newtonsoft.Json;

namespace FileMerge.Helpers
{
    /// <summary>
    /// 配置帮助
    /// </summary>
    public static class ConfigHelper
    {
        private static List<Configuration> configs;

        /// <summary>
        /// 当前配置
        /// </summary>
        public static List<Configuration> Configs
        {
            get
            {
                if (configs != null) return configs;

                var configDir = $"{Directory.GetCurrentDirectory()}\\config";

                if (!Directory.Exists(configDir))
                {
                    configDir = $"{Directory.GetParent(Directory.GetCurrentDirectory())}\\config";

                    if (!Directory.Exists(configDir))
                    {
                        Console.WriteLine("Error: Configuration directory not found.");
                        return null;
                    }
                }

                var files = Directory.GetFiles(configDir, "*.conf", SearchOption.AllDirectories);

                if (files == null || files.Length == 0)
                {
                    Console.WriteLine("Error: Configuration not found.");
                    return null;
                }

                configs = new List<Configuration>();

                foreach (var file in files)
                {
                    string json;

                    try { json = File.ReadAllText(file); }

                    catch (IOException e)
                    {
                        Console.WriteLine($"Error: Failed to read configuration {file}. {e.Message}");
                        continue;
                    }

                    Configuration config;

                    try { config = JsonConvert.DeserializeObject<Configuration>(json); }

                    catch (Exception e)
                    {
                        Console.WriteLine("Error: Failed to parse configuration. " + e.Message);
                        continue;
                    }

                    if (config == null) continue;

                    config.Path = file;
                    configs.Add(config);
                }

                return configs;
            }
        }
    }
}
